import type { Form } from "@/interface/formData";
import { dayjs, ElMessage } from "element-plus";
import { computed, ref } from "vue";
import formData from "@/tool/data/formData";
import axios from "axios";
import { useUserStore } from "@/stores/userStore";

export default function () {

    const { useridentityfer, username_store } = useUserStore();
    const TableDataAll = ref<Form[]>([]);
    let formatTable = ref<Form[]>([]);


    //请求后端数据

    async function getWorks() {
        await axios.get("/api/student/allWork")
            .then(response => {
                TableDataAll.value = response.data.data;
                formatTableData(TableDataAll.value);
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    async function REQ_receiveWork(jobId: number) {
        await axios.get(`/api/student/receiveWorks/${useridentityfer}/${username_store}/${jobId}`)
            .then(response => {
                if (response.data.code === 200) {
                    ElMessage.success("成功接取");
                }else if(response.data.code === 201){
                    ElMessage.info("请不要重复接取");
                }
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    //搜索框数据
    let title = ref("");
    let type = ref("");
    let priceLow = ref<number | null>(null);
    let priceHeight = ref<number | null>(null);
    const flitItem = ref({ title, type, priceLow, priceHeight });
    const form = formData();

    //搜索内容重置
    const resetForm = () => {
        title.value = "";
        type.value = "";
        priceLow.value = null;
        priceHeight.value = null;
    };



    //table数据过滤
    function formatTableData(data: Form[]) {
        formatTable.value = data.map((item) => ({
            ...item,
            status: item.status === "1" ? "待审核" :
                item.status === "2" ? "审核通过" :
                    item.status === "3" ? "审核失败" : item.status,
            process: item.process === "1" ? "待接取" :
                item.process === "2" ? "已接取" :
                    item.process === "3" ? "经行中" :
                        item.process === "4" ? "已完成" :
                            item.process === "5" ? "已结算" : item.process,
            jobType: item.jobType === "1" ? "零工" :
                item.jobType === "3" ? "短期兼职" :
                    item.jobType === "2" ? "长期兼职" : item.jobType,
            publisher: item.userName,
        }))
        console.log("formatTable::", formatTable.value)
    }

    const tableData = computed(() => {
        if (
            !type.value &&
            !title.value &&
            !priceLow.value &&
            !priceHeight.value
        )
            return formatTable.value;
        return formatTable.value.filter((item: Form) => {
            const matchType = type.value
                ? item.jobType.includes(type.value)
                : true;
            const matchTitle = title.value
                ? item.title.includes(title.value)
                : true;
            const matchPriceMin = priceLow.value
                ? item.salary > priceLow.value
                : true;
            const matchPriceMax = priceHeight.value
                ? item.salary < priceHeight.value
                : true;
            return matchType && matchTitle && matchPriceMin && matchPriceMax;
        });
    });

    //价格的格式化展示
    const formatPrice = (row: Form, column: Form, cellValue: number) => {
        return `${cellValue}元/小时`;
    };

    //表格时间的格式化处理
    const formatTablrDate = (row: Form, column: Form, cellValue: Date) => {
        if (!cellValue) return ""; // 如果没有值，直接返回空字符串
        // 使用 JavaScript 的 Date 对象进行格式化
        const date = new Date(cellValue);
        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, "0"); // 获取月份，+1 是因为 getMonth() 返回的月份是从 0 开始的
        const day = String(date.getDate()).padStart(2, "0"); // 获取日期
        return `${year}-${month}-${day}`; // 返回格式化的日期字符串
    };


    function receiveWork(row?: Form, $event?: any) {
        let jobId = 0;
        if (row != null) {
            event?.stopPropagation();
            jobId = row.id;
        }
        if (row == null) {
            jobId = currentRowData.value.id;
        }
        REQ_receiveWork(jobId);
    }


    //当前行数据
    const currentRowData = ref<Form>({
        //存储一条数据的变量
        id: 0,
        userIdentifier:0,
        userName: "",
        jobType: "",
        status: "",
        title: "",
        maxPeople: 0,
        description: "",
        salary: 0,
        process: "",
        takersId: [],
        takersName: [],
        createdTime: new Date(),
        startTime: new Date(),
        endTime: new Date(),
        publishTime: new Date(),
        autoPublish: true,
    });
    //侧边栏的时间格式
    const formattedEndTime = computed({
        get: () => dayjs(currentRowData.value.endTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.endTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });
    const formattedStartTime = computed({
        get: () => dayjs(currentRowData.value.startTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.startTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });
    const formattedPublishTime = computed({
        get: () => dayjs(currentRowData.value.publishTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.publishTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });
    const formatDrawerDate = ref({
        formattedEndTime: formattedEndTime,
        formattedStartTime: formattedStartTime,
        formattedPublishTime: formattedPublishTime,
    });
    const isOpenDrawer = ref(false);
    //行点击函数
    const RowClick = (row: Form) => {
        isOpenDrawer.value = true;
        currentRowData.value = { ...row };
    };
    const isEdit = ref(true);
    return {
        tableData,
        flitItem,
        formatPrice,
        formatTablrDate,
        resetForm,
        RowClick,
        currentRowData,
        isOpenDrawer,
        isEdit,
        formatDrawerDate,
        // receiveBtn,
        getWorks,
        receiveWork,
    };
}
